import Cookies from 'js-cookie'

const TOKEN_NAME = window.btoa('token')

/**
 * 编码字符串
 * @param {string} str 待编码字符串
 * @returns {string} url编码+base64字符串
 */
function encode(str) {
  return window.btoa(window.encodeURIComponent(str))
}

/**
 * 解码字符串
 * @param {string} str 待编码字符串
 * @returns {string} url解码+base64解码字符串
 */
function decode(str) {
  return window.decodeURIComponent(window.atob(str))
}

export function getToken() {
  return Cookies.get(TOKEN_NAME) && decode(Cookies.get(TOKEN_NAME)) || null
}

export function setToken(token, expires) {
  Cookies.set(TOKEN_NAME, encode(token), { expires: expires })
}

export function removeToken() {
  return Cookies.remove(TOKEN_NAME)
}
